import { useRef } from 'react';
import type { ActionType } from '@ant-design/pro-components';
import type { FormInstance } from 'antd';

interface ExtendedActionType<P> extends ActionType {
  onSearch: (values: P) => Promise<void>;
  onResetAndSearch: () => void;
  onReset: () => void;
}

interface UsePageActionOptions<P> {
  formRef: React.MutableRefObject<FormInstance | undefined>;
  handleFinish: (values: P) => Promise<any>;
  handleReset: () => void;
}

/**
 * 处理页面 ActionRef 的 Hook
 */
const usePageAction = <P extends Record<string, any>>(
  options: UsePageActionOptions<P>
) => {
  const { formRef, handleFinish, handleReset } = options;

  // 创建 pageRef
  const pageRef = useRef<ExtendedActionType<P>>({
    onReset: () => {
      formRef.current?.resetFields();
      handleReset();
    },
    onSearch: async (values: P) => {
      await handleFinish(values);
    },
    onResetAndSearch: () => {
      formRef.current?.resetFields();
      handleReset();
    },
  } as ExtendedActionType<P>);

  return {
    pageRef,
  };
};

export default usePageAction; 